const Router = require('koa-router');
const CourseRouter = new Router();
const CourseService = require('../service/CourseService');
const R = require('../utils/R');
const { isNull } = require('../utils/validators');
const Validators = require('../utils/validators');

CourseRouter.prefix('/api/v1/course');
CourseRouter.get('/list',async (ctx, next) => {
    let {pageSize, pageNum, ...criteria } = ctx.request.query;
    Validators.isNull(pageSize, 'pageSize').isNull(pageNum, 'pageNum');
    let data = await CourseService.findAll(pageSize, pageNum, criteria );
    ctx.pageSize = pageSize;
    ctx.pageNum = pageNum;
    ctx.body = R.okData(data)
})

CourseRouter.get('/info/:id', async (ctx, next) => {
    let courseId = ctx.params.id;
    Validators.isNull(courseId, 'courseId');
    let data = await CourseService.findAllAttrById(courseId);
    ctx.body = R.okData(data)
})

CourseRouter.post('/save', async (ctx, next) => {
    let course = ctx.request.body;
    Validators.isNull(course.courseName, 'courseName').isNull(course.classRoomId, 'classRoomId')
    isNull(course.duration, 'duration').isNull(course.grade, 'grade').isNull(course.teacherId, 'teacherId')
    .isNull(course.categoryId, 'categoryId').isNull(course.classTimeId, 'classTimeId')
    await CourseService.saveCourse(course);
    ctx.body = R.okMsg('添加成功');
})

CourseRouter.post('/delete', async (ctx, next) => {
    let course = ctx.request.body;
    Validators.isNull(course.courseId, 'courseId');
    await CourseService.deleteCourse(course.courseId);
    ctx.body = R.okMsg('删除成功')
})

CourseRouter.post('/update', async (ctx, next) => {
    let course = ctx.request.body;
    Validators.isNull(course.courseName, 'courseName').isNull(course.classRoomId, 'classRoomId')
    isNull(course.duration, 'duration').isNull(course.grade, 'grade').isNull(course.teacherId, 'teacherId')
    .isNull(course.categoryId, 'categoryId').isNull(course.classTimeId, 'classTimeId').isNull(course.courseId, 'courseId');
    await CourseService.updateCourse(course);
    ctx.body = R.okMsg('修改成功')
})

CourseRouter.post('/examine', async (ctx, next) => {
    let course = ctx.request.body;
    Validators.isNull(course.courseId, 'courseId').isNull(course.status, 'status').isHave(course.status, ['0', '1', '2'], 'status');
    await CourseService.updateStatus(course);
    ctx.body = R.okMsg('修改成功')
})

module.exports = CourseRouter